package com.rn.gypsophila.grpc;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Description: Subject对象带有绑定观察者到 Client 对象和从 Client 对象解绑观察者的方法。
 *
 * @author 然诺
 * @date 2021/04/06
 */
@Slf4j
public class Subject {
    public static final Cache<String, Callback> CALLBACK_CACHE = Caffeine.newBuilder()
            .maximumSize(10000)
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .removalListener((k, v, removalCause) -> {
                log.warn("RemovalListener->缓存移除元素");
                log.warn(String.valueOf(k));
            }).build();

    public Subject() {
    }

    public void addCallback(String key, Callback callback) {
        CALLBACK_CACHE.put(key, callback);
    }

    public void romveCallback(String key) {
        CALLBACK_CACHE.invalidate(key);
    }

    public void execute(List<String> keys) {
        for (String key : keys) {
            Callback callback = CALLBACK_CACHE.getIfPresent(key);
            if (callback != null) {
                callback.onSuccess();
                CALLBACK_CACHE.invalidate(key);
            } else {
                log.info("[{}]-非本客户端提交，直接忽略...", key);
            }
        }
    }
}
